package com.liseen.loader
{
	import flash.display.Loader;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.HTTPStatusEvent;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	/**
	 * swf加载器
	 * @author Liseen
	 * 
	 */	
	public class SWFLoadItem extends LoadItem
	{
		public var loader:Loader;
		public var byteLoader:URLLoader;
		
		public function SWFLoadItem(url:String, type:String)
		{
			super(url, type);
		}
		
		override public function onErrorHandler(event:ErrorEvent):void
		{
			super.onErrorHandler(event);
		}
		
		override public function stop():void
		{
			try
			{
				if (byteLoader)
				{
					byteLoader.close();
				}
			}
			catch(e:Error)
			{
			}
			super.stop();
		}
		
		override public function load():void
		{
			super.load();
			byteLoader = new URLLoader();
			byteLoader.dataFormat = URLLoaderDataFormat.BINARY;
			byteLoader.addEventListener(Event.OPEN,onStartedHandler,false,0,true);
			byteLoader.addEventListener(ProgressEvent.PROGRESS,onProgressHandler,false,0,true);
			byteLoader.addEventListener(IOErrorEvent.IO_ERROR,onErrorHandler,false,0,true);
			byteLoader.addEventListener(Event.COMPLETE,onByteSWFLoadedHandle,false,0,true);
			byteLoader.load(urlRequest);
		}
		
		private function onByteSWFLoadedHandle(event:Event):void
		{
			loader = new Loader();
			loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onCompleteHandler, false, 0, false);
			loader.loadBytes(event.target.data,loadContext);
		}
		
		override public function onCompleteHandler(event:Event):void
		{
			loader.contentLoaderInfo.removeEventListener(Event.COMPLETE,onCompleteHandler);
			try
			{
				content = loader.contentLoaderInfo;
			}
			catch(e:SecurityError)
			{
				content = null;
			};
			super.onCompleteHandler(event);
		}
		
		override protected function cleanListeners():void
		{
			if (byteLoader)
			{
				byteLoader.removeEventListener(ProgressEvent.PROGRESS, onProgressHandler, false);
				byteLoader.removeEventListener(Event.COMPLETE, onByteSWFLoadedHandle, false);
				byteLoader.removeEventListener(IOErrorEvent.IO_ERROR, onErrorHandler, false);
				byteLoader.removeEventListener(Event.OPEN, onStartedHandler, false);
				byteLoader.removeEventListener(HTTPStatusEvent.HTTP_STATUS, super.onHttpStatusHandler, false);
				byteLoader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, super.onSecurityErrorHandler, false);
			}
		}
		
		override public function destroy():void
		{
			stop();
			cleanListeners();
			content = null;
			loader = null;
			byteLoader = null;
		}
	}
}